<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col :span="24" :xs="24">
        <!-- 数据筛选表单 -->
        <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="100px">
          <!-- 数据筛选表单组件 -->
          <el-form-item label="角色编码" prop="roleKey">
            <el-input v-model="queryParams.roleKey" placeholder="请输入角色编码" clearable size="small"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" size="small" placeholder="请选择">
              <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>

          <!-- 数据筛选操作按钮 -->
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="3">
            <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAdd">新增角色</el-button>
          </el-col>
        </el-row>

        <!-- 数据表格 -->
        <el-table v-loading="loading" :data="roleList">
          <!-- 数据表格列 -->
          <el-table-column label="角色ID" align="center" prop="roleId" />
          <el-table-column label="角色名称" align="center" prop="roleName" />
          <el-table-column label="角色编码" align="center" prop="roleKey" />
          <el-table-column label="排序" align="center" prop="roleSort" />
          <el-table-column label="状态" align="center" prop="status">
            <template #default="scope">
              <el-tag v-if="scope.row.status === '0'" size="small" type="success">正常</el-tag>
              <el-tag v-else-if="scope.row.status === '1'" size="small" type="danger">禁用</el-tag>
            </template>
          </el-table-column>

          <!-- 数据行操作按钮 -->
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button size="small" type="text" icon="el-icon-key" @click="handleMenu(scope.row)">
                分配菜单
              </el-button>
              <el-button size="small" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button size="small" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 数据分页加载 -->
        <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[5, 10, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </el-col>
    </el-row>

    <!-- 添加修改role对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <!-- 数据编辑表单组件 -->
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="roleKey">
          <el-input v-model="form.roleKey" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="排序" prop="roleSort">
          <el-input v-model="form.roleSort" placeholder="请输入排序编号" />
        </el-form-item>
      </el-form>

      <!-- 数据提交操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :title="menuTitle" v-model="menuDialogFormVisible" width="300px">
      <el-form :model="menuForm">
        <el-tree ref="menuTree" :data="menuTreeData" show-checkbox node-key="menuId" :props="defaultProps"
          :default-checked-keys="defaultCheckedKeys" />
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="menuDialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAuthMenu">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
/** 导入axios Api */
import { listRoleByPage, getRole, addRole, updateRole, deleteRole, authMenu } from '@/api/role'
import { listMenu, getMenu } from '@/api/menu'
export default {
  name: 'Role',
  data() {
    return {

      // 新增菜单分配相关数据
      menuDialogFormVisible: false,
      menuTitle: '',
      menuTreeData: [],
      menuForm: {
        roleId: null,
        menuIds: []
      },
      defaultProps: {
        children: 'children',
        label: 'menuName'
      },
      // 状态类型
      statusOptions: [
        {
          value: '0',
          label: '正常'
        },
        {
          value: '1',
          label: '禁用'
        }
      ],
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // 当前页
      pageNum: 0,
      // 每页数据量
      pageSize: 0,
      // Role表格数据
      roleList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 数据查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 5,
        roleKey: null,
        status: null
      },
      // 数据编辑表单
      form: {},
      // 表单数据校验规则
      rules: {
        roleName: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        roleKey: [
          { required: true, message: '角色编码不能为空', trigger: 'blur' }
        ],
        roleSort: [
          { required: true, message: '排序不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询Role数据列表 */
    getList() {
      this.loading = true
      listRoleByPage(this.queryParams).then((response) => {
        console.log("API返回数据：", response.data.list);
        this.roleList = response.data.list
        this.total = response.data.total
        this.pageNum = this.queryParams.pageNum
        this.pageSize = this.queryParams.pageSize
        this.loading = false
      })
    },
    /** 处理分页 */
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.getList()
    },

    /** 数据编辑对话框取消按钮 */
    cancel() {
      this.open = false
      this.resetForm()
    },

    /** 数据编辑表单清空 */
    resetForm() {
      this.form = {
        roleId: null,
        roleName: null,
        roleKey: null,
        roleSort: null
      }
    },

    /** 数据筛选参数重置按钮 */
    resetQueryParams() {
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 5
    },

    /** 数据筛选搜索按钮 */
    handleQuery() {
      this.resetQueryParams()
      this.getList()
      this.$message.success('查询成功')
    },

    /** 数据筛选重置按钮 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 5,
        roleId: null,
        roleKey: null,
        status: null
      }
      this.getList()
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.resetForm()
      this.open = true
      this.title = '添加Role'
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.resetForm()
      getRole(row.roleId).then((response) => {
        this.form = response.data
        this.open = true
        this.title = '修改Role'
      })
    },

    /** 数据提交按钮 */
    submitForm: function () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.roleId === null) {
            addRole(this.form).then((response) => {
              this.$message.success(response.msg)
              this.open = false
              this.title = ''
              this.getList()
            })
          } else {
            updateRole(this.form).then((response) => {
              this.$message.success(response.msg)
              this.open = false
              this.title = ''
              this.getList()
            })
          }
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除名称为"' + row.roleName + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function () {
          return deleteRole(row.roleId)
        })
        .then(() => {
          this.getList()
          this.$message.success('删除成功')
        })
        .catch(() => { })
    },

    /** 处理分配菜单 */
    async handleMenu(row) {
      this.menuForm.roleId = row.roleId  // 使用roleId而不是menuId
      this.menuTitle = `为角色[${row.roleName}]分配菜单`
      this.menuDialogFormVisible = true

      try {
        // 并行加载数据
        const [menusRes, roleRes] = await Promise.all([
          listMenu(),  // 获取所有菜单
          getRole(row.roleId)  // 获取角色已有菜单
        ])

        // 设置菜单树数据
        this.menuTreeData = menusRes.data || []

        // 获取角色已有的菜单ID
        const menuIds = roleRes.data?.menus?.map(item => item.menuId) || []

        // 设置选中项
        await this.$nextTick()
        if (this.$refs.menuTree) {
          this.$refs.menuTree.setCheckedKeys(menuIds)
        }
      } catch (error) {
        console.error('加载菜单数据失败:', error)
        this.$message.error('加载菜单数据失败: ' + (error.response?.data?.msg || error.message))
      }
    },

    /** 提交分配菜单 */
    submitAuthMenu() {
      this.menuForm.menuIds = this.$refs.menuTree.getCheckedKeys()
      authMenu(this.menuForm).then(response => {
        this.$message.success(response.msg)
        this.menuDialogFormVisible = false
      }).catch(error => {
        this.$message.error('分配菜单失败: ' + (error.response?.data?.msg || error.message))
      })
    }
    // async submitAuthMenu() {
    //   try {
    //     const checkedKeys = this.$refs.menuTree.getCheckedKeys()
    //     const halfCheckedKeys = this.$refs.menuTree.getHalfCheckedKeys()

    //     const { data } = await authMenu({
    //       roleId: this.menuForm.roleId,
    //       menuIds: [...checkedKeys, ...halfCheckedKeys]
    //     })

    //     this.$message.success(data.msg || '菜单分配成功')
    //     this.menuDialogFormVisible = false
    //   } catch (error) {
    //     console.error('分配菜单失败:', error)
    //     const errorMsg = error.response?.data?.msg || error.message || '分配失败'
    //     this.$message.error(`分配菜单失败: ${errorMsg}`)
    //   }
    // }

  }


}
</script>
